package com.ltc.cdr.tests;

import java.io.File;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import com.ltc.cdr.domain.CdrVolume;
import com.ltc.cdr.domain.FCdrDetail;

public class Test {
	private static EntityManagerFactory emf;
	private static EntityManager em;
	private static String ROOTPATH = "D:/CDRData";

	public static void main(String[] arg) {
		
		Timer timer = new Timer();
		timer.schedule(new TimerTask(){
			@Override
			public void run() {
				
				// Start transaction
				debutTest();
				
				readindirector readdrection = new readindirector();
				File f = new File(ROOTPATH);
				List<String> filepaths = readdrection.findFiles(f);
				

				for (String path : filepaths) {
					if (path != null && !path.contains("gData")) {
						List<CdrVolume> cdr = readdrection.txtread(path);
								saveCDR(cdr);
						}
					}
				// end
				finTest();
				
			}

			}, 0, 5000);
	}

	private static List<CdrVolume> findAllCDR(){
		Query q =  em.createQuery("SELECT c FROM CdrVolume c");
		List<CdrVolume> cdrdb = q.getResultList();
		return cdrdb;
	}
	
	private static void saveCDR(List<CdrVolume> cdrFromTxt) {

		String filenam = cdrFromTxt.get(0).getFilename().substring(cdrFromTxt.get(0).getFilename().lastIndexOf("ConvertData")+14,cdrFromTxt.get(0).getFilename().length());
		FCdrDetail cdrDetail= em.find(FCdrDetail.class,filenam);
		if(cdrDetail==null){ 
			em.getTransaction().begin();
			FCdrDetail cdrDetailnew = new FCdrDetail();
			cdrDetailnew.setFileid(filenam);
			cdrDetailnew.setDesction(cdrFromTxt.get(0).getFilename());
			for(CdrVolume cdr:cdrFromTxt){
				em.persist(cdr);
			}
			em.persist(cdrDetailnew);
			em.getTransaction().commit();
		}
	}

	private static void debutTest() {
		emf = Persistence.createEntityManagerFactory("jpa");
		em = emf.createEntityManager();
	}

	private static void finTest() {
		em.close();
		emf.close();
	}
}